package com.heima.schedule.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.RedisCacheService;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskinfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class TaskinfoServiceImpl extends ServiceImpl<TaskinfoMapper, Taskinfo> implements TaskinfoService {
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    private RedisCacheService redisCacheService;

    @Autowired
    private TaskinfoMapper taskinfoMapper;

    /**
     * 定时同步数据 mysql->redis
     */
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData() {
        log.info("数据同步到缓存");
        //清除缓存
        clearCache();
        //数据库同步到缓存
        //查询小于当前时间+五分钟的数据
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(
                Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, calendar.getTime())
        );
        if (CollUtil.isNotEmpty(taskinfos)) {
            for (Taskinfo taskinfo : taskinfos) {
                addTaskToCache(taskinfo);
            }
        }
        log.info("缓存同步结束");
    }

    /**
     * 清除redis中的缓存
     */
    private void clearCache() {
        // 删除缓存中未来数据集合和当前消费者队列的所有key
        Set<String> future_key = redisCacheService.scan(ScheduleConstants.FUTURE + "*");
        Set<String> topic_key = redisCacheService.scan(ScheduleConstants.TOPIC + "*");
        redisCacheService.delete(future_key);
        redisCacheService.delete(topic_key);
    }

    /**
     * 未来数据定时刷新
     */
    @Scheduled(cron = "0 0/1 * * * ? ")
    public void refresh() {
        log.info("定时任务执行了");

        //加锁 ->过期时间30秒
        String lock = redisCacheService.tryLock("FUTURE_TASK_SYNC", 1000 * 30);

        if (StringUtils.isNotEmpty(lock)) {
            //获取所有redis中未来的key
            Set<String> keys = redisCacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String future_key : keys) {
                //获取小于当前时间的数据 task
                Set<String> taskInfo = redisCacheService.zRangeByScore(future_key, 0, System.currentTimeMillis());
                if (CollUtil.isNotEmpty(taskInfo)) {
                    //替换FUTURE 为TOPIC
                    String topic_key = future_key.replace(ScheduleConstants.FUTURE, ScheduleConstants.TOPIC);
                    //通过redis管道替换
                    redisCacheService.refreshWithPipeline(future_key, topic_key, taskInfo);
                }
            }
            log.info("定时任务结束");
        }

    }

    /**
     * 添加任务
     *
     * @param task
     * @return
     */
    @Override
    public long addTask(Taskinfo task) {
        //保存任务到数据库
        Boolean success = addTaskToDb(task);

        if (success) {
            //添加任务到redis
            addTaskToCache(task);
        }
        return task.getTaskId();
    }

    /**
     * 添加任务到redis
     *
     * @param task
     */
    private void addTaskToCache(Taskinfo task) {
        //获取当前时间五分钟之后的毫秒值
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, 5);
        long timeInMillis = calendar.getTimeInMillis();

        String key = task.getTaskType() + "_" + task.getPriority();

        //执行时间小于等于当前时间存入list ->>等待执行
        if (task.getExecuteTime().getTime() <= System.currentTimeMillis()) {
            //存入list
            redisCacheService.lLeftPush(ScheduleConstants.TOPIC + key, JSON.toJSONString(task));
        } else if (task.getExecuteTime().getTime() <= timeInMillis) {//执行时间小于等于当前时间+五分钟 存入zset ->>等待执行
            //存入五分钟之后的数据到 zset
            redisCacheService.zAdd(ScheduleConstants.FUTURE + key, JSON.toJSONString(task), task.getExecuteTime().getTime());
        }
    }

    /**
     * 取消任务
     *
     * @param taskId
     * @return
     */
    @Override
    public Boolean cancelTask(Long taskId) {

        Boolean flag = false;

        //删除任务并更新日志
        Taskinfo taskinfo = updateDb(taskId, ScheduleConstants.CANCELLED);

        //删除redis中的数据
        if (taskinfo != null) {
            removeTaskFromCache(taskinfo);
            flag = true;
        }

        return false;
    }

    /**
     * 按照类型和优先级拉取任务
     *
     * @param type
     * @param priority
     * @return
     */
    @Override
    public Taskinfo poll(int type, int priority) {
        Taskinfo taskinfo = null;
        String key = type + "_" + priority;
        String taskInfoStr = redisCacheService.lRightPop(ScheduleConstants.TOPIC + key);
        if (StringUtils.isNotEmpty(taskInfoStr)) {
            taskinfo = JSONArray.parseObject(taskInfoStr, Taskinfo.class);
            //删除任务并更新日志
            updateDb(taskinfo.getTaskId(), ScheduleConstants.EXECUTED);
        }
        return taskinfo;
    }

    /**
     * 删除redis中的数据
     *
     * @param taskinfo
     */
    private void removeTaskFromCache(Taskinfo taskinfo) {
        String key = taskinfo.getTaskType() + "_" + taskinfo.getPriority();

        if (taskinfo.getExecuteTime().getTime() <= System.currentTimeMillis()) {
            //删除list中的任务
            redisCacheService.lRemove(ScheduleConstants.TOPIC + key, 0, JSON.toJSONString(taskinfo));

        } else {
            //删除zSet中的数据
            redisCacheService.zRemove(ScheduleConstants.FUTURE + key, JSON.toJSONString(taskinfo));
        }
    }

    /**
     * 删除任务并更新日志
     *
     * @param taskId
     * @param cancelled
     * @return
     */
    private Taskinfo updateDb(Long taskId, int cancelled) {
        //删除任务
        removeById(taskId);

        //更新日志
        TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
        taskinfoLogs.setStatus(cancelled);
        taskinfoLogsMapper.updateById(taskinfoLogs);

        return baseMapper.selectById(taskId);
    }

    /**
     * 保存任务到数据库
     *
     * @param task
     * @return
     */
    private Boolean addTaskToDb(Taskinfo task) {

        Boolean flag = true;
        try {
            //保存taskSave表
            save(task);

            //保存takeInfoLogs表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(task, taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED); //初始化状态
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag = true;

        } catch (BeansException e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }
}
